package com.darcye.clear.work;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.List;

import com.darcye.clear.reader.MenuFileReader;
import com.darcye.clear.reader.OnFileReadListener;
import com.darcye.clear.reader.entity.BaseEntity;
import com.darcye.clear.reader.entity.MenuEntity;
import com.darcye.clear.utils.DeleteLogger;
import com.darcye.clear.utils.FileList;

/**
 * 清理menu文件，其所在的目录必须是res/menu* 目录
 * @author Darcy
 * @date 2014-9-30 下午2:19:17
 * @version V1.0
 */
public class MenuWorker extends BaseWorker {

	private DeleteLogger logger = new DeleteLogger("Menu");
	
	public MenuWorker(JavaWorker worker){
		mUsedMenuIdSet.addAll(worker.getUsedMenuIdSet());
	}

	public void execute() {
		FileList fl = new FileList(getResourcePath());
		List<File> totalMenuFiles = fl.recurseListFiles(new FilenameFilter() {
			File pFile;
			public boolean accept(File dir, String name) {
				pFile = dir.getParentFile();
				return pFile.getName().startsWith("menu");
			}
		});
		MenuFileReader reader;
		String menuFilename,menuId;
		for (File menuFile : totalMenuFiles) {
			menuFilename = menuFile.getName();
			menuId = menuFilename.substring(0, menuFilename.lastIndexOf("."));
			if(mUsedMenuIdSet.contains(menuId)){
				reader = new MenuFileReader(menuFile);
				try {
					reader.setOnFileReadListener(new OnFileReadListener() {
						public void onReaded(BaseEntity entity) {
							MenuEntity menuEntity = (MenuEntity)entity;
							mUsedLayoutIdSet.addAll(menuEntity.getLayoutIdSet());
							mUsedDrawableIdSet.addAll(menuEntity.getDrawableIdSet());
							mUsedStringIdSet.addAll(menuEntity.getStringIdSet());
							mUsedIntegerIdSet.addAll(menuEntity.getIntegerIdSet());
							mUsedBoolIdSet.addAll(menuEntity.getBoolIdSet());
							mUsedIdIdSet.addAll(menuEntity.getIdIdSet());
						}
					}).scan();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}else{
				if(isIgnoreDeleteFile(menuFile))
					 continue;
				backupDelFile(menuFile);
				logger.log(menuId,menuFile.getPath());
				menuFile.delete();
			}
		}
		logger.finish();
	}

}
